package net.celisdelafuente.java.Acacia.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class Environment {
	
	private String apphome = System.getProperty("user.home") + "/acacia";
	private int tcpport = 8080;
	private String datadir = apphome + "/data";
	private String dburl = "jdbc:derby:/home/ecelis/acacia/data/acaciadb;create=true;user=APP;";
			/*"'jdbc:derby:" + datadir + 
			"/acaciadb;create=true;user=APP;'";*/
	private String appContextPath = "/acacia";
	private String warFile = apphome + "/acacia.war";
	private String isbnkey = "WJCUBZZD";
	
	public String getIsbnkey() {
		return isbnkey;
	}

	public void setIsbnkey(String isbnkey) {
		this.isbnkey = isbnkey;
	}

	public String getApphome() {
		return apphome;
	}

	public void setApphome(String apphome) {
		this.apphome = apphome;
	}

	public int getTcpport() {
		return tcpport;
	}

	public void setTcpport(int tcpport) {
		this.tcpport = tcpport;
	}

	public String getDatadir() {
		return datadir;
	}

	public void setDatadir(String datadir) {
		this.datadir = datadir;
	}

	public String getDburl() {
		return dburl;
	}

	public void setDburl(String dburl) {
		this.dburl = dburl;
	}
	
	public String getAppContextPath() {
		return appContextPath;
	}

	public void setAppContextPath(String appcontextpath) {
		this.appContextPath = appcontextpath;
	}

	public String getWarFile() {
		return warFile;
	}

	public void setWarFile(String warFile) {
		this.warFile = warFile;
	}

	public void configure() {
		Properties appsettings = new Properties();
		InputStream fis = null;
		try {
			fis = new FileInputStream(System.getProperty("user.home") + 
					"/acacia/config.properties");
			appsettings.load(fis);
			
			if(appsettings.getProperty("apphome") != null)
				setApphome(appsettings.getProperty("apphome"));
			
			if (appsettings.getProperty("tcpport") != null) {
				setTcpport(Integer.parseInt(
						appsettings.getProperty("tcpport")));
			}
			
			if(appsettings.getProperty("datadir") != null) {
				setDatadir(getApphome() + "/" +
						appsettings.getProperty("datadir"));
			}
			
			if (appsettings.getProperty("dburl") != null) {
				setDburl("jdbc:derby:" + getDatadir() + "/" +
						appsettings.getProperty("dburl"));
			}
			
			if(appsettings.getProperty("isbnkey") != null) {
				setIsbnkey(appsettings.getProperty(isbnkey));
			}
			
		} catch (IOException e) {
			// TODO Do something
			e.printStackTrace();
		} finally {
			if(fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					// TODO something
					e.printStackTrace();
				}
			}
		}
		
		File appdir = new File(apphome);
		if(!appdir.exists())
			new File(apphome).mkdir();
		
		File dbdir = new File(datadir);
		if(!dbdir.exists())
			new File(datadir).mkdir();
	}
	
	public Environment() {
		
	}
	
}
